package com.hdax.search.controller;


import com.alibaba.fastjson.JSON;
import com.hdax.search.config.ElasticSearchConfig;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.json.JSONString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 整合es
 */
@RestController
public class GuMallElasticSearch {


    @Autowired
    private RestHighLevelClient client;

    @RequestMapping("/gaga")
    public String hah(){
        System.out.println(client);
        return "ddd";
    }

    /**
     * 测试数据到es
     */
    @RequestMapping("/test")
    public void haha() throws IOException {
        IndexRequest indexRequest=new IndexRequest("users");
        indexRequest.id("1");
        User user=new User();
        user.setUserName("侯林娜");
        user.setAge(20);
        user.setGender("女");
        String jsonString = JSON.toJSONString(user);
        indexRequest.source(jsonString, XContentType.JSON);
        IndexResponse index = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
    }


    /**
     * 检索数据
     */
    @RequestMapping("/l")
    public void l() throws IOException {
        //1、创建一个检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("bank");
        //指定检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建检索条件
//        searchSourceBuilder.query();
//        searchSourceBuilder.from();
//        searchSourceBuilder.size();
//        searchSourceBuilder.aggregation();
        //带条件查询
        searchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
        //分组查询年龄分组
        TermsAggregationBuilder fenzu = AggregationBuilders.terms("ageAgg").field("age").size(10);
        searchSourceBuilder.aggregation(fenzu);
        //查询平均年龄
        AvgAggregationBuilder avgAge = AggregationBuilders.avg("ageAvg").field("age");
        searchSourceBuilder.aggregation(avgAge);
        System.out.println("检索条件"+searchSourceBuilder.toString());


        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //分析结果
        System.out.println("查询值："+search.toString());
//        Map map = JSON.parseObject(search.toString(), Map.class);
        //1、获取所有查到的数据
        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit documentFields : hits1) {
            String sourceAsString = documentFields.getSourceAsString();
            //将his数据转为指定的javaBean对象
            JSON.parseObject(sourceAsString,User.class);
        }
        //获取查询到的分组信息
        Aggregations aggregations = search.getAggregations();
        //获取所有聚合信息
//        List<Aggregation> aggregations1 = aggregations.asList();
//        for (Aggregation aggregation : aggregations1) {
//            System.out.println(aggregation.getName());
//        }
        //获取指定的聚合
        Terms ageAgg = aggregations.get("ageAgg");
        for (Terms.Bucket bucket : ageAgg.getBuckets()) {
            String keyAsNumber = bucket.getKeyAsString();
            System.out.println("年龄:"+keyAsNumber);
        }

    }


    @Data
    class User{
        private String userName;
        private String gender;
        private int age;
    }
}
